<template>
  <div class="image-selector">
    <div class="selector-header">
      <h3 class="selector-title">
        <el-icon><Picture /></el-icon>
        选择图片
      </h3>
      <div class="selector-actions">
        <el-button 
          type="primary" 
          :icon="Upload"
          @click="goToUpload"
        >
          上传新图片
        </el-button>
        <el-button 
          :icon="Search"
          @click="toggleSearch"
        >
          {{ showSearch ? '隐藏搜索' : '显示搜索' }}
        </el-button>
      </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-section" v-show="showSearch">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索图片名称或标签..."
        clearable
        @input="handleSearch"
        @clear="handleSearchClear"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <!-- 快速筛选 -->
      <div class="quick-filters">
        <el-button-group>
          <el-button 
            :type="filterType === 'all' ? 'primary' : ''"
            size="small"
            @click="setFilter('all')"
          >
            全部
          </el-button>
          <el-button 
            :type="filterType === 'recent' ? 'primary' : ''"
            size="small"
            @click="setFilter('recent')"
          >
            最近上传
          </el-button>
          <el-button 
            :type="filterType === 'ai-success' ? 'primary' : ''"
            size="small"
            @click="setFilter('ai-success')"
          >
            AI识别成功
          </el-button>
          <el-button 
            :type="filterType === 'unused' ? 'primary' : ''"
            size="small"
            @click="setFilter('unused')"
          >
            未使用
          </el-button>
        </el-button-group>
      </div>
    </div>
    
    <!-- 当前选中的图片 -->
    <div class="selected-image" v-if="selectedImage">
      <div class="selected-header">
        <span class="selected-title">当前选中图片</span>
        <el-button 
          text 
          size="small"
          @click="clearSelection"
        >
          取消选择
        </el-button>
      </div>
      
      <div class="selected-card">
        <div class="selected-image-container">
          <img 
            :src="selectedImage.fileUrl" 
            :alt="selectedImage.originalName"
            class="selected-preview"
          />
        </div>
        
        <div class="selected-info">
          <h4 class="selected-name">{{ selectedImage.originalName }}</h4>
          <div class="selected-meta">
            <span>{{ formatFileSize(selectedImage.fileSize) }}</span>
            <span>{{ selectedImage.width }}×{{ selectedImage.height }}</span>
            <span>{{ formatTime(selectedImage.createdAt) }}</span>
          </div>
          
          <div class="selected-tags" v-if="selectedImage.tags && selectedImage.tags.length > 0">
            <el-tag
              v-for="tag in selectedImage.tags.slice(0, 5)"
              :key="tag"
              size="small"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
            <el-tag
              v-if="selectedImage.tags.length > 5"
              size="small"
              type="info"
            >
              +{{ selectedImage.tags.length - 5 }}
            </el-tag>
          </div>
          
          <div class="ai-status" :class="getAiStatusClass(selectedImage.aiRecognitionStatus)">
            {{ getAiStatusText(selectedImage.aiRecognitionStatus) }}
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图片网格 -->
    <div class="images-grid">
      <div class="grid-header">
        <span class="grid-title">
          {{ filteredImages.length > 0 ? `共 ${filteredImages.length} 张图片` : '暂无图片' }}
        </span>
        <div class="grid-controls">
          <el-slider
            v-model="gridSize"
            :min="120"
            :max="200"
            :step="20"
            :show-tooltip="false"
            style="width: 100px;"
          />
        </div>
      </div>
      
      <div 
        class="images-container"
        :style="{ '--grid-size': gridSize + 'px' }"
        v-loading="loading"
      >
        <div
          v-for="image in paginatedImages"
          :key="image.id"
          class="image-item"
          :class="{ 'selected': selectedImage?.id === image.id }"
          @click="selectImage(image)"
        >
          <div class="image-container">
            <img 
              :src="image.fileUrl" 
              :alt="image.originalName"
              class="image-preview"
              @load="handleImageLoad"
            />
            
            <!-- 选中指示器 -->
            <div class="selection-indicator" v-if="selectedImage?.id === image.id">
              <el-icon><Check /></el-icon>
            </div>
            
            <!-- AI状态指示器 -->
            <div class="ai-indicator" :class="getAiStatusClass(image.aiRecognitionStatus)">
              <el-icon><MagicStick /></el-icon>
            </div>
          </div>
          
          <div class="image-info">
            <div class="image-name" :title="image.originalName">
              {{ image.originalName }}
            </div>
            <div class="image-meta">
              <span>{{ formatFileSize(image.fileSize) }}</span>
              <span>{{ image.width }}×{{ image.height }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="totalPages > 1">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="filteredImages.length"
          layout="prev, pager, next"
          small
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="filteredImages.length === 0 && !loading" class="empty-state">
      <el-icon size="48" color="rgba(255,255,255,0.5)"><Picture /></el-icon>
      <h3>{{ getEmptyMessage() }}</h3>
      <el-button 
        type="primary" 
        :icon="Upload"
        @click="goToUpload"
      >
        上传图片
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Picture, Upload, Search, Check, MagicStick 
} from '@element-plus/icons-vue'
import type { ImageModel } from '@/types'
import { formatFileSize, formatTime, debounce } from '@/utils'

interface Props {
  images?: ImageModel[]
  loading?: boolean
  selectedImage?: ImageModel
}

interface Emits {
  (e: 'select-image', image: ImageModel): void
  (e: 'load-images', params: any): void
}

const props = withDefaults(defineProps<Props>(), {
  images: () => [],
  loading: false
})

const emit = defineEmits<Emits>()
const router = useRouter()

// 响应式数据
const showSearch = ref(false)
const searchKeyword = ref('')
const filterType = ref('all')
const gridSize = ref(160)
const currentPage = ref(1)
const pageSize = ref(20)

// 计算属性
const filteredImages = computed(() => {
  let filtered = [...props.images]
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(image => 
      image.originalName.toLowerCase().includes(keyword) ||
      image.tags?.some(tag => tag.toLowerCase().includes(keyword))
    )
  }
  
  // 类型筛选
  switch (filterType.value) {
    case 'recent':
      filtered = filtered.sort((a, b) => 
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      ).slice(0, 50)
      break
    case 'ai-success':
      filtered = filtered.filter(image => image.aiRecognitionStatus === 'SUCCESS')
      break
    case 'unused':
      filtered = filtered.filter(image => image.usageCount === 0)
      break
  }
  
  return filtered
})

const totalPages = computed(() => Math.ceil(filteredImages.value.length / pageSize.value))

const paginatedImages = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredImages.value.slice(start, end)
})

// 防抖搜索
const debouncedSearch = debounce(() => {
  currentPage.value = 1
}, 300)

// 方法
const selectImage = (image: ImageModel) => {
  emit('select-image', image)
}

const clearSelection = () => {
  emit('select-image', null as any)
}

const toggleSearch = () => {
  showSearch.value = !showSearch.value
}

const handleSearch = () => {
  debouncedSearch()
}

const handleSearchClear = () => {
  searchKeyword.value = ''
  currentPage.value = 1
}

const setFilter = (type: string) => {
  filterType.value = type
  currentPage.value = 1
  
  // 根据筛选类型加载数据
  const params: any = {}
  
  switch (type) {
    case 'recent':
      params.sortBy = 'createdAt'
      params.sortDir = 'desc'
      params.size = 50
      break
    case 'ai-success':
      params.aiStatus = 'SUCCESS'
      break
    case 'unused':
      params.minUsageCount = 0
      params.maxUsageCount = 0
      break
  }
  
  emit('load-images', params)
}

const handlePageChange = (page: number) => {
  currentPage.value = page
}

const handleImageLoad = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.classList.add('loaded')
}

const goToUpload = () => {
  router.push({ name: 'Upload' })
}

const getAiStatusClass = (status: string) => {
  switch (status) {
    case 'SUCCESS': return 'status-success'
    case 'FAILED': return 'status-failed'
    default: return 'status-pending'
  }
}

const getAiStatusText = (status: string) => {
  switch (status) {
    case 'SUCCESS': return 'AI识别成功'
    case 'FAILED': return 'AI识别失败'
    default: return 'AI识别中'
  }
}

const getEmptyMessage = () => {
  switch (filterType.value) {
    case 'recent': return '暂无最近上传的图片'
    case 'ai-success': return '暂无AI识别成功的图片'
    case 'unused': return '暂无未使用的图片'
    default: return searchKeyword.value ? '没有找到符合条件的图片' : '还没有上传任何图片'
  }
}

// 生命周期
onMounted(() => {
  emit('load-images', {})
})
</script>

<style scoped>
.image-selector {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.selector-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.selector-actions {
  display: flex;
  gap: 10px;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
}

.search-section :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-bottom: 15px;
}

.search-section :deep(.el-input__inner) {
  color: white;
}

.quick-filters {
  display: flex;
  justify-content: center;
}

/* 选中图片样式 */
.selected-image {
  margin-bottom: 20px;
}

.selected-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.selected-title {
  font-size: 14px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
}

.selected-card {
  display: flex;
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.3);
  border-radius: 15px;
  padding: 15px;
  gap: 15px;
}

.selected-image-container {
  width: 80px;
  height: 80px;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
}

.selected-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.selected-info {
  flex: 1;
  min-width: 0;
}

.selected-name {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.selected-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 10px;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 10px;
}

.ai-status {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  font-weight: 500;
}

.status-success {
  background-color: rgba(103, 194, 58, 0.8);
  color: white;
}

.status-failed {
  background-color: rgba(245, 108, 108, 0.8);
  color: white;
}

.status-pending {
  background-color: rgba(230, 162, 60, 0.8);
  color: white;
}

/* 图片网格样式 */
.images-grid {
  margin-bottom: 20px;
}

.grid-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.grid-title {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.grid-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.images-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(var(--grid-size), 1fr));
  gap: 15px;
  min-height: 200px;
}

.image-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.image-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.image-item.selected {
  background: rgba(64, 158, 255, 0.2);
  border: 2px solid #409EFF;
}

.image-container {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
  opacity: 0;
}

.image-preview.loaded {
  opacity: 1;
}

.selection-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: #409EFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
}

.ai-indicator {
  position: absolute;
  bottom: 8px;
  right: 8px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.image-info {
  padding: 10px;
}

.image-name {
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 5px;
}

.image-meta {
  display: flex;
  justify-content: space-between;
  font-size: 10px;
  color: rgba(255, 255, 255, 0.6);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: rgba(255, 255, 255, 0.7);
}

.empty-state h3 {
  margin: 15px 0;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-selector {
    padding: 15px;
  }
  
  .selector-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .selector-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .selected-card {
    flex-direction: column;
  }
  
  .selected-image-container {
    width: 100%;
    height: 200px;
  }
  
  .grid-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .images-container {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
  }
}
</style>